package com.ds.server.comet;

import com.ds.common.ConfigCode;
import com.ds.common.JDSException;
import com.ds.context.JDSCometContext;
import com.ds.context.JDSContext;
import com.ds.engine.ConnectInfo;
import com.ds.engine.ConnectionHandle;
import com.ds.engine.JDSSessionHandle;
import com.ds.msg.Msg;
import com.ds.server.JDSClientService;
import com.ds.server.JDSServer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class GWCometHandle extends AbstractCometHandle {

    public GWCometHandle(JDSClientService client, JDSSessionHandle sessionHandle, String systemCode) throws JDSException {
	super(client, sessionHandle, systemCode);

    }

    public void receive(String receiveStr) throws JDSException {
	logger.info("receive user:[" + getConnectInfo().getLoginName() + "] ");
	logger.info(receiveStr);
    }

    public boolean send(String msgString) throws JDSException {
	logger.info(msgString);
	return super.send(msgString);
    }

    class ClearSession implements Runnable {
	private ConnectionHandle sessionHandle;

	private ConnectInfo connectInfo;

	private String systemCode;

	ClearSession(ConnectInfo connectInfo, ConnectionHandle handle, String systemCode) {
	    this.sessionHandle = handle;
	    this.connectInfo = connectInfo;
	    this.systemCode = systemCode;
	}

	public void run() {
	    try {
		Set<JDSSessionHandle> sessionHandleList = JDSServer.getInstance().getSessionHandleList(connectInfo);
		ConfigCode configCode=JDSServer.getClusterClient().getSystem(systemCode).getConfigname();
		for (JDSSessionHandle handle : sessionHandleList) {
		    if (!handle.toString().equals(sessionHandle.toString())) {
			JDSClientService client = JDSServer.getInstance().getJDSClientService(handle, configCode);
			if (client != null && client.getConnectInfo() != null) {
			    client.getConnectionHandle().disconnect();
			}
		    }

		}
	    } catch (JDSException e) {
		e.printStackTrace();
	    }

	}

    }

    public void connect(JDSContext context) throws JDSException

    {

	if (context instanceof JDSCometContext) {
	    JDSCometContext cometContext = (JDSCometContext) context;
	    this.request = (HttpServletRequest) cometContext.getHttpRequest();
	    this.response = (HttpServletResponse) cometContext.getHttpResponse();
	} else {
	    throw new JDSException("用户未登录！", JDSException.PROCESSDEFINITIONERROR);
	}

	if (this.connectInfo == null) {
	    connectInfo = this.getClient().getConnectInfo();
	}

	if (this.connectInfo == null) {
	    throw new JDSException("用户未登录！", JDSException.PROCESSDEFINITIONERROR);
	}

	Set<JDSSessionHandle> sessionHandleList = JDSServer.getInstance().getSessionHandleList(connectInfo);
	// 注销掉多余的SESSION
	List<JDSSessionHandle> newsessionHandleList = new ArrayList<JDSSessionHandle>();

	if (sessionHandleList != null) {
	    newsessionHandleList.addAll(sessionHandleList);
	    for (JDSSessionHandle handle : newsessionHandleList) {
		if (handle != null && !handle.getSessionID().toString().equals(context.getSessionId())) {
		    if (JDSServer.getInstance().getConnectTimeCache().get(handle) != null) {
			JDSServer.getInstance().disconnect(handle);
		    }

		}

	    }

	}

	client.connect(connectInfo);
	logger.info("user:" + connectInfo.getLoginName() + "[" + sessionHandle.getSessionID() + "] cometLogin success");
	int k = 0;
	while (isClose) {
	    JDSClientService client = this.getClient();
	    ConnectInfo connectionInfo = client.getConnectInfo();
	    if (client != null && connectionInfo != null) {

		Long lastLoginTime = checkTime.get(context.getSessionId());

		Long lastHeartTime = checkCommandHeart.get(context.getSessionId());

		// 每300秒激活一次在线时间
		if (lastLoginTime == null) {
		    lastLoginTime = System.currentTimeMillis();
		    checkTime.put(context.getSessionId(), lastLoginTime);
		    ConnectionServer connectTask = new ConnectionServer(client, connectInfo);	   
		    getCommandService(connectInfo.getUserID()).submit(connectTask);

		}

		if (System.currentTimeMillis() - lastLoginTime > 300 * 1000) {
		    checkTime.put(context.getSessionId(), System.currentTimeMillis());
		    ConnectionServer connectTask = new ConnectionServer(client, connectInfo);
		    getCommandService(connectInfo.getUserID()).submit(connectTask);
		}

		// 每300秒激活一次在线时间
		if (lastHeartTime == null) {
		    lastHeartTime = System.currentTimeMillis();
		    checkCommandHeart.put(context.getSessionId(), lastHeartTime);
		}

		    send(HEARTKEY);
		    try {
			Thread.sleep(5000);
		    } catch (InterruptedException e) {
			isClose = false;
			send(e.getMessage());

		    }
		    k = k + 1;

		} else {
		    isClose = false;
		    client.getConnectionHandle().disconnect();

		}

	  
	}
	send("sessionId is  null,  place login frist!");
    }

    public void disconnect() throws JDSException {
	
	super.disconnect();
    }

    @Override
    public boolean repeatMsg(Msg msg, JDSSessionHandle handle) throws JDSException {
	
	return false;
    }
}
